package cn.juforg.mail;

import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import cn.juforg.constant.Constants;

public class MailConstructor {
	private String userName ;
	private String passWord ;
	private MimeMessage mimeMsg;
	private Session session ;
	private Properties props ;
	private Multipart mp;
	Authenticator auth;
	
	public class EmailAutherticator extends Authenticator{
		
		public PasswordAuthentication getPasswordAuthenticator(){
			return new PasswordAuthentication(userName, passWord);
		}
		
		final MailConstructor mc;

		public EmailAutherticator() {
			super();
			mc = MailConstructor.this;
		}
		
	}

	public MailConstructor() {
	}
	
	public MailConstructor(String smtp) {
		setSmtpHost(smtp);
		createMimeMessage();
	}
	
	public void setSmtpHost(String hostName){
		if (props==null) 
			props = System.getProperties();
			props.put("mail.smtp.host", hostName);
			auth = new EmailAutherticator();
			props.put("mail.smtp.auth", "true");
		
	}
	
	public boolean createMimeMessage(){
		try {
			session = Session.getDefaultInstance(props,null);
			mimeMsg = new MimeMessage(session);
			mp = new MimeMultipart();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public void setNeedAuth(boolean need){
		if (props==null) {
			props = System.getProperties();
		}
		props.put("mail.smtp.auth", ""+need);
	}
	
	public void setNamePass(String name , String pass){
		this.userName = name;
		this.passWord = pass;
	}
	
	public boolean setSubject(String mailSubject){
		try {
			mimeMsg.setSubject(mailSubject);
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean setBody(String mailBody){
		BodyPart bp = new MimeBodyPart();
		try {
			bp.setContent(
					(new StringBuilder(" <meta http-equiv=Content-Type content=text/html; charset=gb2312>")).append(mailBody+Constants.USERNAME+"\n"+Constants.COMPUTERNAME).toString(),"text/html;charset=GB2312"
					);
			mp.addBodyPart(bp);
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean addFileAffix(String fileName){
		try {
		BodyPart bp = new MimeBodyPart();
		FileDataSource fds = new FileDataSource(fileName);
		bp.setDataHandler(new DataHandler(fds));
		bp.setFileName(fds.getName());
		mp.addBodyPart(bp);
		} catch (MessagingException e) {
			e.printStackTrace();
			return false ;
		}
		return true;
	}
	
	public boolean setFrom(String from){
		try {
			mimeMsg.setFrom(new InternetAddress(from));
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean setTo(String to){
		try {
			mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
		} catch (AddressException e) {
			e.printStackTrace();
			return false;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean setCopyTo(String copyTo){
		if (copyTo==null || "".equals(copyTo)) {
			return false;
		}
		try {
			mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(copyTo));
		} catch (AddressException e) {
			e.printStackTrace();
			return false;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean sendOut(){
		try {
			mimeMsg.setContent(mp);
			mimeMsg.saveChanges();
			Session mailsession = Session.getInstance(props, auth);
			Transport transport = mailsession.getTransport("smtp");
			transport.connect((String)props.getProperty("mail.smtp.host"), userName, passWord);
			transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
			transport.close();
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		return true ;
	}
	
	public static void main(String args[]){
		String mailbody = " <meta http-equiv=Content-Type content=text/html; charset=gb2312> <div align=center><a href=http://www.baidu.com> \u606D\u559C\u4F60\uFF0C\u4E2D\u5956\u5566\uFF01 </a> </div>";
        MailConstructor themail = new MailConstructor("smtp.sina.com");
        themail.setNeedAuth(true);
        if(!themail.setSubject("\u6807\u989822"))
            return;
        if(!themail.setBody(mailbody))
            return;
        if(!themail.setFrom("juforg@sina.com"))
            return;
        if(!themail.setTo("334501190@qq.com"))
            return;
        if(!themail.addFileAffix("D:\\RECYCLE.BIN\\111912141"))
            ;
        themail.setNamePass("juforg@sina.com", "psuso666");
        if(!themail.sendOut())
            return;
        else
            return;
	}
}
